package com.turing.data.scripts.yhlc.filter

import com.alibaba.fastjson.JSON
import com.turing.common.entity.TextVO
import com.turing.common.util.FileUtils
import com.turing.data.engine.TextUtils
import com.turing.data.engine.utils.ScriptsUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO
import org.apache.commons.lang.SerializationUtils
import com.turing.data.engine.utils.RegexExtract

/**
 * @description: 银行理财 - 份额
 * @author: mazhishen
 */

class Share_30251_46_filter {

    static List< TaskElementVO.DrawResultVO > doConvert(DependParamsVO dependParams){
        def REGEX_BACKUP = /.*赎回份额.*/
        def REGEX_BACKUP_1 = "确认份额"
        def REGEX_BACKUP_2 = /申购.{0,1}份额/
        def REGEX_BACKUP_3 = /认购.{0,1}份额/

        List< TaskElementVO.DrawResultVO > trueValueSet = new ArrayList<>()
        List<TaskElementVO.DrawResultVO > resultVOs = ScriptsUtils.tryInitResult(dependParams)
        def set = new HashSet()
        if (resultVOs!=null && resultVOs.size()>0) {
            for (int i = 0; i < resultVOs.size(); i++) {
                def drawResultVO = resultVOs.get(i)
                def childTaskSn = drawResultVO.childTaskSn
                if(null == childTaskSn || childTaskSn == ""){
                    return resultVOs
                }
                def start = drawResultVO.start
                def end = drawResultVO.end
                def text = drawResultVO.text
                text = text.replaceAll("\n","")
                def textPathMap = dependParams.textPathMap
                def rawPath = textPathMap.get(drawResultVO.childTaskSn)
                def rawText = FileUtils.loadJson(rawPath)
                def expandOffset = 0
                //往前10个字符搜索
                while( expandOffset < 20 && start > expandOffset ){
                    def expandString = rawText.substring(start-expandOffset,start)
                    if( expandString =~ REGEX_BACKUP || expandString =~ REGEX_BACKUP_1
                        || expandString =~ REGEX_BACKUP_2 || expandString =~ REGEX_BACKUP_3
                    )
                    {
                        drawResultVO.text = drawResultVO.text.replaceAll(/[，]/,",")
                        trueValueSet.add(drawResultVO)
                        set.add(drawResultVO.text)
                        return trueValueSet
                    }
                    expandOffset ++
                }
            }
        }
        //先使用正则查找精确查找
        try{
            if(trueValueSet.size()==0) {

                String REGEX0 = /(申购.{0,1}份额|认购.{0,1}份额|赎回.{0,1}份额)[:：]\d.+?\d份/
                println dependParams.JSONTextMap.size()
                dependParams.JSONTextMap.forEach(
                        { childTaskSn, jsonText ->
                            RegexExtract.doRuleExtract(REGEX0, childTaskSn, dependParams, jsonText, trueValueSet)
                        }
                )
                if (trueValueSet.size()>0){
                    def getFinalReg = /\d.+?\d(?=份)/
                    def matcher = trueValueSet[0].text =~ getFinalReg
                    if (matcher.count>0){
                        trueValueSet[0].businessValue = matcher[0] as String
                        trueValueSet[0].setType(1)
                        return trueValueSet
                    }else {
                        trueValueSet.clear()
                    }
                }
            }
        }catch (Exception e2){
            e2.printStackTrace()
        }


        //第二次依赖模型再找
        def REGEX_BACKUP_4 = "总份额"
        def REGEX_BACKUP_5 = "期末份额"
        if (resultVOs!=null && resultVOs.size()>0) {
            for (int i = 0; i < resultVOs.size(); i++) {
                def drawResultVO = resultVOs.get(i)
                def childTaskSn = drawResultVO.childTaskSn
                if(null == childTaskSn || childTaskSn == ""){
                    return resultVOs
                }
                def start = drawResultVO.start
                def end = drawResultVO.end
                def text = drawResultVO.text
                text = text.replaceAll("\n","")
                def textPathMap = dependParams.textPathMap
                def rawPath = textPathMap.get(drawResultVO.childTaskSn)
                def rawText = FileUtils.loadJson(rawPath)
                def expandOffset = 0
                //往前10个字符搜索
                while( expandOffset < 20 && start > expandOffset ){
                    def expandString = rawText.substring(start-expandOffset,start)
                    if( expandString =~ REGEX_BACKUP_4 || expandString =~ REGEX_BACKUP_5)
                    {
                        drawResultVO.text = drawResultVO.text.replaceAll(/[，]/,",")
                        trueValueSet.clear()
                        trueValueSet.add(drawResultVO)
                        set.add(drawResultVO.text)
                        return trueValueSet
                    }
                    expandOffset ++
                }
            }
        }

        //使用正则
        //子任务id
        String childTaskId = ""

        try{
            if(trueValueSet.size()==0) {

                String REGEX = /赎回份额:.{1,20}份/
                println dependParams.JSONTextMap.size()
                dependParams.JSONTextMap.forEach(
                        { childTaskSn, jsonText ->
                            childTaskId =childTaskSn
                            RegexExtract.doRuleExtract(REGEX, childTaskSn, dependParams, jsonText, trueValueSet)
                        }
                )

                if (trueValueSet.size() > 0) {
                    def textPathMap = dependParams.textPathMap
                    def childTaskSn = trueValueSet[0].childTaskSn
                    def rawPath = textPathMap.get(childTaskSn)
                    def rawText = FileUtils.loadJson(rawPath)
                    def JSONTextMap = dependParams.JSONTextMap
                    def fileTextStr = ""
                    fileTextStr = JSONTextMap.get(childTaskSn)
                    def text = trueValueSet[0].text
                    def startOffset = text.indexOf("赎回份额:") + "赎回份额:".length()
                    def endOffset = -"份".length()
                    TaskElementVO.DrawResultVO objectNew = (TaskElementVO.DrawResultVO) SerializationUtils.clone(trueValueSet[0])
                    objectNew = TextUtils.correctPositionInfoByOffset(objectNew, startOffset, endOffset, fileTextStr, rawText)
                    trueValueSet.clear()
                    trueValueSet.add(objectNew)
                    return trueValueSet
                }
            }
        }
        catch (Exception e){
            e.printStackTrace()
        }

        //处理关键词和对应的值跨行问题：20210802-惠享添利赎回确认书
        try {
            String REGEX0 = /(申购.{0,1}份额|认购.{0,1}份额|赎回.{0,1}份额)/
            def resultMatcherList = matching(dependParams,REGEX0,-7)
            if(resultMatcherList.size()>0){
                TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
                //默认结果选第一个,对正则后的内容进行处理
                def originalText = resultMatcherList[0].objContent
                def getFinalReg = /\d.+?\d(?=份)/
                //处理返回的文本
                def matcherText = originalText =~ getFinalReg
                def finalText = originalText
                if(matcherText.count>0){finalText = matcherText[0]}
                //设置返回的文本
                defaultDrawResultVO.text = finalText
                defaultDrawResultVO.businessValue = defaultDrawResultVO.text
                defaultDrawResultVO.childTaskSn = childTaskId
                defaultDrawResultVO.para_info  =  [resultMatcherList[0].lineId]
                //处理返回文本高亮
                //将处理后的正则结果和原来该行的所有内容进行正则匹配，找出起始位置，默认全文
                def positionMatcher = resultMatcherList[0].objContent =~ getFinalReg
                def positionStart = 0
                def positionEnd = originalText.length()
                while (positionMatcher.find()){
                    positionStart = positionMatcher.start()
                    positionEnd = positionMatcher.end()
                }
                defaultDrawResultVO.businessValue = defaultDrawResultVO.text.replaceAll(/[，]/,",")
                defaultDrawResultVO.type = 1
                defaultDrawResultVO.pos_info = [positionStart,positionEnd]
                trueValueSet.clear()
                trueValueSet.add(defaultDrawResultVO)
                return  trueValueSet
            }
        } catch (Exception e1) {
            e1.printStackTrace()
        }

        //返回空值
        TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
        defaultDrawResultVO.text = ""
        trueValueSet.add(defaultDrawResultVO)
        return  trueValueSet

    }


    //通过正则获得一行内容
    static List<TextVO.Line> matching(DependParamsVO dependParams, String reg, int step){
        //返回结果的集合
        List<TextVO.Line> resultMatcherList = new ArrayList<>()
        //表格类型：通过json文本找到关键词的所在行
        dependParams.getJSONTextMap().forEach({ childTaskSn, jsonText ->
            List<TextVO> textVOList = JSON.parseArray(jsonText, TextVO.class)
            for (i in 0..<textVOList.size()) {
                //获得段落列表
                List<TextVO.Paragraph> listParagraph = textVOList[i].paragraphs
                for (j in 0..<listParagraph.size()) {
                    //获得每行的具体信息
                    List<TextVO.Line> lines = listParagraph[j].lines
                    for (k in 0..<lines.size()) {
                        //每行内容匹配关键词
                        def keyWordMatcher = lines[k].objContent =~ reg
                        if (keyWordMatcher.count > 0) {
                            //结果对象，关键词的下一局
                            resultMatcherList.add(lines[k + step])
                        }
                    }
                }
            }
        })
        return resultMatcherList
    }

}
